#coding=utf-8

from uliweb import expose
import generic.views as g_views

get_test_url = g_views.get_url('/tests/test')
layout = 'tests_test_layout.html'
#layout = 'events_layout.html'
def __begin__():
    from uliweb import function
    return function('require_login')()
    
def boolean_convert(b, obj):
    if b:
        return '<div class="ui-icon ui-icon-check"></div>'
    else:
        return '<div class="ui-icon ui-icon-closethick"></div>'

@expose('/tests/test/list')
def tests_test_list():
    from uliweb.utils.generic import ListView
    from uliweb.orm import get_model
    from query import create_test_query
    from uliweb import request
    from uliweb.core.html import Tag
    from uliweb import orm
    from sqlalchemy.sql import select
    from sqlalchemy.sql import and_, or_, not_,outerjoin
    import time, sys
    import datetime
    from datetime import date
    
    
    Sysfunction = get_model('sysfunction')
    Testplan_functions = get_model('testplan_functions')
    Tasks_develop = get_model('tasks_develop')
    Testplan = get_model('testplan')
    query_view = create_test_query(url_for(tests_test_list))
    c = query_view.run()
    
    query = None
    condition = None
    
    if c.get('system'):
#        print '===',c['system']
        condition = (Testplan_functions.c.system == (int(c['system']))) & condition
    if c.get('kfzx'):
        condition = (Testplan_functions.c.kfzx == (int(c['kfzx']))) & condition
            
    #开发部门，开发主管只能看自已中心的测试计划，非主管看自已系统对应的测试计划
    if c.get('only_mine')=='1':
#        print '====+++',c['only_mine']
        if request.user.department == '2':
            if request.user.is_gm:
                condition = (Testplan_functions.c.system.in_(request.user.kfzx.kfzx_systems.ids())) & condition
            else:
                condition = (Testplan_functions.c.system.in_(request.user.users_systems.ids())) & condition
#                print 'ffff',condition,request.user.users_systems.ids()
    
    if c.get('function_type'):
            condition = (Sysfunction.c.function_type.in_(c['function_type'])) & condition
#
#    if c.get('change_status'):
#            condition = (Testplan_functions.c.change_status == (int(c['change_status']))) & condition
#
#    if c.get('using_status'):
#            condition = (Testplan_functions.c.using_status == (int(c['using_status']))) & condition
#
#    if c.get('business_degree'):
#            condition = (Testplan_functions.c.business_degree == (int(c['business_degree']))) & condition

#    if c.get('trading_frequency'):
#            condition = (Testplan_functions.c.trading_frequency == (int(c['trading_frequency']))) & condition

            
    if c.get('version_date_begin'):
            condition = (Testplan_functions.c.testplan.in_(select([Testplan.c.id],and_(Testplan.c.version_date >= c['version_date_begin'])))) & condition
    if c.get('version_date_end'):
            condition = (Testplan_functions.c.testplan.in_(select([Testplan.c.id],and_(Testplan.c.version_date <= c['version_date_end'])))) & condition
    
    query = select([Testplan_functions.c.testplan, 
                        Testplan_functions.c.task,
                        Sysfunction.c.function_name,
                        Sysfunction.c.function_code,
                        Sysfunction.c.system,
                        Sysfunction.c.function_type,
                        '"requirement"',
                        '"req_id"',
                        Sysfunction.c.business_rules,
                        Testplan_functions.c.change_status,
                        Sysfunction.c.business_degree,
                        Sysfunction.c.trading_route_origin,
                        Sysfunction.c.route_origin_code,
                        Sysfunction.c.trading_route_downstream,
                        Sysfunction.c.route_downstream_code,
                        Sysfunction.c.trading_frequency,
                        Sysfunction.c.daily_visit,
                        Sysfunction.c.creator_user,
                        Testplan_functions.c.open_status,
                        Testplan_functions.c.open_secverify,
                        Testplan_functions.c.test_point
                        ],
                    condition,
                    from_obj=[Testplan_functions.table.outerjoin(Sysfunction.table,and_(Sysfunction.c.id == Testplan_functions.c.function))])
#    print '=====', query
#    def test_id(value, obj):
#        return str(Tag('a', obj['test_id'], href="/tests/test/%s/edit" % obj['id']))
        
    fields = ['testplan','task',
      {'name':'function_name','verbose_name':'基本属性/功能名称', 'width':80, 'prop':Sysfunction.function_name},
      {'name':'function_code','verbose_name':'基本属性/功能代码', 'width':80, 'prop':Sysfunction.function_code},
      {'name':'system','verbose_name':'基本属性/所属系统', 'width':80, 'prop':Sysfunction.system},
      {'name':'function_type','verbose_name':'基本属性/功能类型', 'width':80, 'prop':Sysfunction.function_type},
      {'name':'requirement','verbose_name':'基本属性/准开发需求名称', 'width':80},
      {'name':'req_id','verbose_name':'基本属性/准开发需求编号', 'width':80},
      {'name':'business_rules','verbose_name':'基本属性/业务规则', 'width':80, 'prop':Sysfunction.business_rules},
      {'name':'change_status','verbose_name':'管理属性/变动状态', 'width':80, 'prop':Testplan_functions.change_status},
      {'name':'business_degree','verbose_name':'使用属性/业务重要程度', 'width':80, 'prop':Sysfunction.business_degree},
      {'name':'trading_route_origin','verbose_name':'使用属性/跨系统交易/交易路径上游', 'width':80, 'prop':Sysfunction.trading_route_origin},
      {'name':'route_origin_code','verbose_name':'使用属性/跨系统交易/上游接口代码', 'width':80, 'prop':Sysfunction.route_origin_code},
      {'name':'trading_route_downstream','verbose_name':'使用属性/跨系统交易/交易路径下游', 'width':80, 'prop':Sysfunction.trading_route_downstream},
      {'name':'route_downstream_code','verbose_name':'使用属性/跨系统交易/下游接口代码', 'width':80, 'prop':Sysfunction.route_downstream_code},
      {'name':'trading_frequency','verbose_name':'使用属性/是否属于访问频度高的交易', 'width':80, 'prop':Sysfunction.trading_frequency},
      {'name':'daily_visit','verbose_name':'使用属性/日均访问量', 'width':80},
      {'name':'creator_user','verbose_name':'使用属性/创建人', 'width':80, 'prop':Sysfunction.creator_user},
      {'name':'open_status','verbose_name':'测试属性/开放使用状态', 'width':80},
      {'name':'open_secverify','verbose_name':'测试属性/开放验密需求', 'width':80},
      {'name':'test_point','verbose_name':'测试属性/功能测试要点', 'width':80},
      ]
    

    def requirement(value,obj):
        task_obj = Tasks_develop.get(Tasks_develop.c.id == obj['task'])
        if task_obj:
            return task_obj.requirement.title
        return ''
    def req_id(value,obj):
        task_obj = Tasks_develop.get(Tasks_develop.c.id == obj['task'])
        if task_obj:
            return task_obj.requirement.req_id
        return ''
    
     

    fields_convert_map = {'requirement':requirement,
                          'req_id':req_id,
                           }
  

    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
#    view =  ListView('test', condition=condition, query=query, fields=fields,
    view =  ListView('testplan_functions', query=query, 
#        condition=condition, 
        fields=fields, 
        rows_per_page=rows_per_page, pageno=pageno, 
        id='test_table', fields_convert_map=fields_convert_map,
        )
    
    
    if 'data' in request.values:
        return json(view.json())
    elif 'download' in request.values:
#        fields_convert_map = {}
        return view.download('testplan_functions.xls', action='download', timeout=0,
            fields_convert_map=fields_convert_map)
    else:
        result = view.run(head=True, body=False)
        result.update({'query_form':query_view.form, 'table':view})
        response.template = 'Testplan_functions_list.html'
        return result

#@expose('/tests/test/add')
#def tests_test_add():
#    from uliweb.utils.generic import AddView
#    from uliweb.orm import get_model
#    from uliweb.form.layout import TableLayout
#    from forms import TestForm
#    from sqlalchemy.sql import and_, or_, not_
#    
#    TestForm.layout_class = TableLayout
#    
#    def post_created_form(fcls, model):
#        #开发部门，开发主管只能增加自已中心的任务，非主管看自已系统对应的任务
#        if request.user.department == '2':
#            if request.user.is_gm:
#                fcls.system.query = request.user.kfzx.kfzx_systems.all()
#            else:
#                fcls.system.query = request.user.users_systems.all()
#        
#    
#    def pre_save(data):
#        System = get_model('system')
#        Test = get_model('test')
#        sys = System.get(System.c.id==int(data['system']))
#        
#        data['modifield_user'] = request.user
##        year = data['created_date'].year
##        v = Test.filter(Test.c.test_id.like('%02d_%s_%%' % (data['system'].abbr, year))).order_by(Test.c.test_id.desc()).values_one('test_id')
##        if not v:
##            data['test_id'] = '%02d_%s_%04d' % (data['system'], year, 1)
##        else:
##            v = v[0]
##            data['req_id'] = v[:8] + '%04d' % (int(v[8:])+1)
#        
#        data['creator_user'] = request.user
#        data['test_id'] = str(sys.abbr)+'_'+data['function_code']
#        
#        
##        data['test_version'] = sys.abbr+'_'+str(data['version_date'])
#    def post_save(obj, data):
#        from sqlalchemy.sql import select, func
#        Test_version = get_model('test_version')
#        
#        p = Test_version(test=obj.id, modified_user=request.user,
#            version_date=data['version_date'],
#            executing_status=data['executing_status'],
#            executing_analysis=data['executing_analysis'],
#            function_result=data['function_result']
#            )
#        p.save()
#        
#        
#    def get_form_field(name):
#        from uliweb.form import TextField,DateField,BooleanField
#        
#        if name == 'version_date':
#            return DateField('投产时间', required=True, html_attrs={'class':'field_date'})
#        if name == 'executing_status':
#            return BooleanField('是否执行测试')
#        if name == 'executing_analysis':
#            return TextField('执行方式分析',rows=20)
#        if name == 'function_result':
#            return TextField('功能测试结果',rows=20)
#        
#        
#    
#    layout = [
#            '-- 基本属性 --',
#            ('sequence_number','system'),('function_name',
#            'function_code',
#            'function_type'),('req_id','req_title','business_rules'),
#            '-- 管理属性 --',
#            ('change_status','review_status'),
#            '-- 使用属性 --',
#            ('business_degree','trading_route_origin','route_origin_code'),
#            ('trading_route_downstream',
#            'trading_frequency','daily_visit'),'function_point',
#            ('subsystem_abbr','subsystem_name'),
#            '-- 测试属性 --',
#            ('using_status',
#            'using_verification_req','must_test_function'),
#            '-- 执行结果分析 --',
#            ('version_date','executing_status'),('executing_analysis',
#            'function_result'),
#            '--  --',
#            ]
#            
#    
#    
#
#    if request.user.department in ('2', '3'):
#        view = AddView('test', url_for(tests_test_add), post_created_form=post_created_form,
#               pre_save=pre_save,
#               layout=layout, get_form_field=get_form_field, 
#               form_cls=TestForm,post_save=post_save)
#        return view.run()
#    else:
#        flash('你不是开发人员和测试人员，无法添加新测试功能点！')
#        return redirect(url_for(tests_test_list))
#    
##    return g_views.generic_add('test', get_test_url, layout=layout, title='增加测试功能点')

#@expose('/tests/test/<int:id>/edit')
#def tests_test_edit(id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import EditView
    from uliweb import request, redirect
    from forms import TestForm
    
    
    Test = get_model('test')
    Test_version= get_model('test_version')
    obj = Test.get(Test.c.id == int(id))
    
    if not obj.can_modified(request.user):
        flash('你无权修改此记录')
        return redirect(url_for(tests_test_view, id=int(id)))
#    if obj.lock_flag and request.user.department != '3':
#        flash('当前测试功能点已经被锁定，不能修改。')
#        return redirect(url_for(tests_test_view, id=int(id)))
    
    def post_created_form(fcls, model, obj):
    #开发部门，开发主管只能增加自已中心的任务，非主管看自已系统对应的任务
        if request.user.department == '2':
            if request.user.is_gm:
                fcls.system.query = request.user.kfzx.kfzx_systems.all()
            else:
                fcls.system.query = request.user.users_systems.all()
        
    fields = ['Sequence_Number','system','function_name',
      'function_code',
      'function_type','req_id','req_title','business_rules',
      'change_status','review_status','business_degree',
      'trading_route_origin','route_origin_code','trading_route_downstream',
      'trading_frequency','daily_visit','using_status',
      'using_verification_req','function_point','must_test_function',
      'subsystem_abbr','subsystem_name',
      {'name':'version_date','verbose_name':'投产时间', 'width':80},
      {'name':'executing_status','verbose_name':'是否执行测试', 'width':80},
      {'name':'executing_analysis','verbose_name':'执行方式分析', 'width':80},
      {'name':'function_result','verbose_name':'功能测试结果', 'width':80},
      ]
    static_fields = [
                {'name':'executing_status','verbose_name':'是否执行测试', 'width':80},
                {'name':'executing_analysis','verbose_name':'执行方式分析', 'width':80},
                {'name':'function_result','verbose_name':'功能测试结果', 'width':80},
            ]
#    def version_date(value,obj):
#        if obj.version_date:
#            return obj.version_date.strftime('%Y-%m-%d')
#        else:
#            return
    #       if obj['version_date']:
    #           return datetime.date(*time.strptime(obj['version_date'], "%Y-%m-%d")[:3])
    #       else:
    #           return ''
    
    def executing_status(value,obj):
        if obj['executing_status']:
            return u'是'
        else:
            return u'否'
    
    def executing_analysis(value,obj):
        return obj.executing_analysis
    
    def function_result(value,obj):
        return obj.function_result  
    
    
    fields_convert_map = {'executing_status':executing_status,
                          'executing_analysis':executing_analysis,
                           'function_result':function_result,}
    
    if request.user.department == '2':     

        
#        def pre_save(obj, data):
#            System = get_model('system')
#            sys = System.get(System.c.id==int(obj.system.id))
#            data['test_version'] = sys.abbr+'_'+str(data['version_date'])
            
        view = EditView('test', ok_url=url_for(tests_test_view, id=int(id)), obj=obj,
            post_created_form=post_created_form, fields=fields,
            static_fields=static_fields,form_cls=TestForm)
#            fields_convert_map=fields_convert_map)
        return view.run()
    elif request.user.department == '3':
        static_fields = ['Sequence_Number','system','function_name',
          'function_code',
          'function_type','req_id','req_title','business_rules',
          'change_status','review_status','business_degree',
          'trading_route_origin','route_origin_code','trading_route_downstream',
          'trading_frequency','daily_visit','using_status',
          'using_verification_req','function_point','must_test_function',
          'subsystem_abbr','subsystem_name',
          {'name':'version_date','verbose_name':'投产时间', 'width':80},
          ]
        
#        view = EditView('test', ok_url=url_for(tests_test_view, id=int(id)), obj=obj, data=data,
#                post_created_form=post_created_form, fields=fields, static_fields=static_fields,
#                pre_save=pre_save)
        view = EditView('test', ok_url=url_for(tests_test_view, id=int(id)), obj=obj,
            post_created_form=post_created_form, fields=fields,
            static_fields=static_fields,form_cls=TestForm,
            fields_convert_map=fields_convert_map)
        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
        return view.run()        
    else:
        flash('你不是开发人员员或测试人员，无法编辑此功能点！')
        return redirect(url_for(tests_test_list))
    
#@expose('/tests/systemfunction/<int:id>/delete')
#def tests_systemfunction_delete(id):
#    from uliweb.orm import get_model
#    
#    Test = get_model('test')
#    obj = Test.get(int(id))
#    
#    if not (request.user.users_systems.has(obj.system) and request.user.department == '2'):
#        flash('你不是对应系统用户，无权删除此测试功能点。')
#        return redirect(url_for(tests_systemfunction_view, id=int(id)))
#
#    
#    return g_views.generic_delete('test', id, get_test_url)

#@expose('/tests/systemfunction/<int:id>')
#def tests_systemfunction_view(id):
#    from uliweb.utils.generic import DetailView
#    from uliweb.orm import get_model
#    from uliweb import orm
#    
#    Test = get_model('test')
#    condition = (Test.c.id == int(id))
#    
#    view = DetailView('test', condition=condition)
#    view.types_convert_map = {orm.BooleanProperty:boolean_convert}
#    return view.run()
#
#@expose('/tests/systemfunction/add')
#def tests_systemfunction_add():
#    from uliweb.utils.generic import AddView
#    from uliweb.orm import get_model
#    from uliweb.form.layout import TableLayout
#    from forms import TestForm
#    from sqlalchemy.sql import and_, or_, not_
#    
#    TestForm.layout_class = TableLayout
#    
#    def post_created_form(fcls, model):
#        #开发部门，开发主管只能增加自已中心的任务，非主管看自已系统对应的任务
#        if request.user.department == '2':
#            if request.user.is_gm:
#                fcls.system.query = request.user.kfzx.kfzx_systems.all()
#            else:
#                fcls.system.query = request.user.users_systems.all()
#        
#    
#    def pre_save(data):
#        System = get_model('system')
#        Test = get_model('test')
#        sys = System.get(System.c.id==int(data['system']))
#        
#        data['modifield_user'] = request.user
##        year = data['created_date'].year
##        v = Test.filter(Test.c.test_id.like('%02d_%s_%%' % (data['system'].abbr, year))).order_by(Test.c.test_id.desc()).values_one('test_id')
##        if not v:
##            data['test_id'] = '%02d_%s_%04d' % (data['system'], year, 1)
##        else:
##            v = v[0]
##            data['req_id'] = v[:8] + '%04d' % (int(v[8:])+1)
#        
#        data['creator_user'] = request.user
#        data['test_id'] = str(sys.abbr)+'_'+data['function_code']
#        
#    
#    layout = [
#            '-- 基本属性 --',
#            ('sequence_number','system'),('function_name',
#            'function_code',
#            'function_type'),('req_id','req_title','business_rules'),
#            '-- 管理属性 --',
#            ('change_status','review_status'),
#            '-- 使用属性 --',
#            ('business_degree','trading_route_origin','route_origin_code'),
#            ('trading_route_downstream',
#            'trading_frequency','daily_visit'),'function_point',
#            ('subsystem_abbr','subsystem_name'),
#            '-- 测试属性 --',
#            ('using_status',
#            'using_verification_req','must_test_function'),
##            '-- 执行结果分析 --',
##            ('version_date','executing_status'),('executing_analysis',
##            'function_result'),
#            '--  --',
#            ]
#            
#    
#    
#
#    if request.user.department in ('2', '3'):
#        view = AddView('test', url_for(tests_systemfunction_add), post_created_form=post_created_form,
#               pre_save=pre_save,
#               layout=layout, 
#               form_cls=TestForm)
#        return view.run()
#    else:
#        flash('你不是开发人员和测试人员，无法添加新测试功能点！')
#        return redirect(url_for(tests_test_list))

#@expose('/tests/systemfunction/list')
#def tests_systemfunction_list():
#    from uliweb.utils.generic import ListView
#    from uliweb.orm import get_model
#    from query import create_test_systemfunction_query
#    from uliweb import request
#    from uliweb.core.html import Tag
#    from uliweb import orm
#    from sqlalchemy.sql import select
#    from sqlalchemy.sql import and_, or_, not_,outerjoin
#    import time, sys
#    import datetime
#    from datetime import date
#    
#    
#    Test = get_model('test')
##    Test_version = get_model('test_version')
#    
#    query_view = create_test_systemfunction_query(url_for(tests_systemfunction_list))
#    c = query_view.run()
#    
#    query = None
#    condition = None
#    
#    if c.get('system'):
#        condition = (Test.c.system == (int(c['system']))) & condition
#            
#    #开发部门，开发主管只能看自已中心的任务，非主管看自已系统对应的任务
#    if request.user.department == '2':
#        if request.user.is_gm:
#            condition = (Test.c.system.in_(request.user.kfzx.kfzx_systems.ids())) & condition
#        else:
#            condition = (Test.c.system.in_(request.user.users_systems.ids())) & condition
#    elif request.user.department == '3':
#    #测试主管可以查看全部任务,非主管看自已系统对应的任务
#        if not request.user.is_gm:
#            condition = (Test.c.system.in_(request.user.users_systems.ids())) & condition
#    
#    
#    if c.get('function_type'):
#            condition = (Test.c.function_type == (int(c['function_type']))) & condition
#
#    if c.get('change_status'):
#            condition = (Test.c.change_status == (int(c['change_status']))) & condition
#
#    if c.get('using_status'):
#            condition = (Test.c.using_status == (int(c['using_status']))) & condition
#
#    if c.get('business_degree'):
#            condition = (Test.c.business_degree == (int(c['business_degree']))) & condition
#
#    if c.get('trading_frequency'):
#            condition = (Test.c.trading_frequency == (int(c['trading_frequency']))) & condition
#
#                    
#    def test_id(value, obj):
#        return str(Tag('a', obj.test_id, href="/tests/systemfunction/%s/edit" % obj.id))
#        
#    fields = ['test_id','sequence_number','system','function_name',
#      'function_code',
#      'function_type','req_id','req_title','business_rules',
#      'change_status','review_status','business_degree',
#      'trading_route_origin','route_origin_code','trading_route_downstream',
#      'trading_frequency','daily_visit','using_status',
#      'using_verification_req','function_point','must_test_function',
#      'subsystem_abbr','subsystem_name',
#      ]
#    
#
#      
#
#    fields_convert_map = {'test_id':test_id}
#    
#
#    
#    pageno = int(request.GET.get('pageno', 0))
#    
#    view =  ListView('test', condition=condition, query=query, fields=fields,
##    view =  ListView('test', query=query, fields=fields,
#        rows_per_page=settings.get_var('PARA/ROWS_PER_PAGE', 10), pageno=pageno, 
#        id='test_table', fields_convert_map=fields_convert_map,
#        )
#    
#    
#    if 'download' in request.GET:
#        return view.download('tests.xls', action='download', timeout=0)
#    else:
#        data = {'query_form':query_view.form}
#        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
#        return g_views.generic_list('test', get_test_url, layout=layout, template='tests_systemfunction_list.html',
#            view=view, data=data)

#@expose('/tests/systemfunction/<int:id>/edit')
#def tests_systemfunction_edit(id):
#    from uliweb.orm import get_model
#    from uliweb.utils.generic import EditView
#    from uliweb import request, redirect
#    from forms import TestForm
#    from uliweb.form.layout import TableLayout
#
#    
#    TestForm.layout_class = TableLayout
#    
#    
#    Test = get_model('test')
##    Test_version= get_model('test_version')
#    obj = Test.get(Test.c.id == int(id))
#    
#    if not obj.can_modified(request.user):
#        flash('你无权修改此记录')
#        return redirect(url_for(tests_test_view, id=int(id)))
#    
#    def post_created_form(fcls, model, obj):
#    #开发部门，开发主管只能增加自已中心的任务，非主管看自已系统对应的任务
#        if request.user.department == '2':
#            if request.user.is_gm:
#                fcls.system.query = request.user.kfzx.kfzx_systems.all()
#            else:
#                fcls.system.query = request.user.users_systems.all()
#        
#    fields = ['sequence_number','system','function_name',
#      'function_code',
#      'function_type','req_id','req_title','business_rules',
#      'change_status','review_status','business_degree',
#      'trading_route_origin','route_origin_code','trading_route_downstream',
#      'trading_frequency','daily_visit','using_status',
#      'using_verification_req','function_point','must_test_function',
#      'subsystem_abbr','subsystem_name',
#      ]
#    
#    
#    layout = [
#            '-- 基本属性 --',
#            ('sequence_number','system'),('function_name',
#            'function_code',
#            'function_type'),('req_id','req_title','business_rules'),
#            '-- 管理属性 --',
#            ('change_status','review_status'),
#            '-- 使用属性 --',
#            ('business_degree','trading_route_origin','route_origin_code'),
#            ('trading_route_downstream',
#            'trading_frequency','daily_visit'),'function_point',
#            ('subsystem_abbr','subsystem_name'),
#            '-- 测试属性 --',
#            ('using_status',
#            'using_verification_req','must_test_function'),
#            '--  --',
#            ]
#    
#    
#    if request.user.department == '2':     
#        
##        def pre_save(obj, data):
##            System = get_model('system')
##            sys = System.get(System.c.id==int(obj.system.id))
##            data['test_version'] = sys.abbr+'_'+str(data['version_date'])
#            
#        view = EditView('test', ok_url=url_for(tests_systemfunction_view, id=int(id)), obj=obj,
#            post_created_form=post_created_form, fields=fields,layout = layout,
#            form_cls=TestForm)
##            fields_convert_map=fields_convert_map)
#        return view.run()
##    elif request.user.department == '3':
##        static_fields = ['Sequence_Number','system','function_name',
##          'function_code',
##          'function_type','req_id','req_title','business_rules',
##          'change_status','review_status','business_degree',
##          'trading_route_origin','route_origin_code','trading_route_downstream',
##          'trading_frequency','daily_visit','using_status',
##          'using_verification_req','function_point','must_test_function',
##          'subsystem_abbr','subsystem_name',
##          {'name':'version_date','verbose_name':'投产时间', 'width':80},
##          ]
##        
###        view = EditView('test', ok_url=url_for(tests_test_view, id=int(id)), obj=obj, data=data,
###                post_created_form=post_created_form, fields=fields, static_fields=static_fields,
###                pre_save=pre_save)
##        view = EditView('test', ok_url=url_for(tests_test_view, id=int(id)), obj=obj,
##            post_created_form=post_created_form, fields=fields,
##            static_fields=static_fields,form_cls=TestForm,
##            fields_convert_map=fields_convert_map)
##        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
##        return view.run()        
#    else:
#        flash('你不是开发人员员，无法编辑此功能点！')
#        return redirect(url_for(tests_test_list))

#@expose('/tests/test/lock')
#def tests_test_lock():
#    from uliweb.orm import get_model
#    
#    Test = get_model('test')
#    
#    for x in request.GET.get('ids').split(','):
#        obj = Test.get(Test.c.id == int(x))
#        obj.lock_flag = True
#        obj.save()
#    
#    return redirect(url_for(tests_test_list))

#@expose('/tests/test/import')
#def tests_test_import():
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.utils.common import log
    
    class ImportView(AddView):
        def on_success(self, data):
            from parse_excel import open_book
            try:
                Test = get_model('test')
                System = get_model('system')
                
                fields = ['sys_name', 'sys_abbr', 'subsystem_name', 'subsystem_abbr',
                    'function_name', 'function_code', ('function_type', 'PARA/FUNCTION_TYPE'),
                    ('change_status', 'PARA/CHANGE_STATUS'), ('using_status', 'PARA/YESNO'),
                    'function_point', ('business_degree', 'PARA/BUSINESS_DEGREE'), 
                    ('trading_frequency', 'PARA/YESNO'), ('across_system', 'PARA/YESNO'),
                    'trading_origin', 'trading_route', 'daily_visit',
                    'test_version', 'version_date', 'function_endtime', ('test_status', 'PARA/TEST_STATUS')]
                f = {}  #字段列表信息
                c = {}  #保存要转换值的字段信息，key为字段名，value为对应settings中的选项
                
                def get_key(key, value):
                    """
                    用于反向根据值来获取key，如[('1', '高'), ('2', '低')]，根据'高'得到'1'
                    """
                    from uliweb import settings
                    
                    s = settings.get_var(key, [])
                    for k, v in s:
                        if isinstance(value, unicode):
                            value = value.encode('utf-8')
                        if isinstance(v, unicode):
                            v = value.encode('utf-8')
                            
                        if value == v:
                            return k
                    
                for i, item in enumerate(fields):
                    if isinstance(item, (tuple, list)):
                        c[item[0]] = item[1]
                        f[i] = item[0]
                    else:
                        f[i] = item
                last_sys = None
                i = 0
                for line in open_book(data['func_file']['filename'], data['func_file']['file'].read(), 
                    log=log, begin=3, fields=f):
                    i += 1
                    d = line.copy()
                    #process value convert
                    for k, v in c.iteritems():
                        if k in d:
                            d_v = d[k]
                            d[k] = get_key(v, d_v)
                            
                    del d['sys_name']
                    abbr = d.pop('sys_abbr')
                    if abbr:
                        s = System.get(System.c.abbr==abbr)
                        last_sys = s
                    if not last_sys:
                        flash('第%d行系统简称查询不到，请检查是否没有填写或大小写不一致' % i)
                        return redirect(url_for(tests_test_import))
                    else:
                        if last_sys.id != data['system']:
                            flash('导入数据中的系统简称与选定系统不符，请检查！')
                            return redirect(url_for(tests_test_import))
                        d['system'] = last_sys
                        t = Test(**d)
                        t.save()
                
                flash('导入成功，共导入%d条记录' % i)
                return redirect(url_for(tests_test_list))
            except Exception, e:
                log.exception(e)
                flash('处理过程有问题，请与程序员联系')
                return redirect(url_for(tests_test_list))
            
    def post_created_form(fcls, model):
        System = get_model('system')
        if request.user.department == '2':
            fcls.system.query = request.user.users_systems.all()
        elif request.user.department == '3':
            fcls.system.query = System.all()
    
    from forms import TestImportForm
    if request.user.department in ('2', '3'):
        view = ImportView('test', url_for(tests_test_list), fields=(), 
            post_created_form=post_created_form, form_cls=TestImportForm)
        return view.run()
    else:
        flash('你不是开发人员和测试人员，无法导入新测试功能点！')
        return redirect(url_for(tests_test_list))
    
@expose('/version/verification/test/import')
def version_verification_test_import(self,id):
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.utils.common import log
    from decimal import Decimal
    
    class ImportView(AddView):
        def on_success(self, data,aaa):
            from parse_excel import open_book
            try:
                Versionverificationtest = get_model('versionverificationtest')
                System = get_model('system')
                Tasks_develop = get_model('tasks_develop')
                Plan = get_model('plan')
                Planedit = get_model('planedit')
                Planexecute = get_model('planexecute')
#                Sysfunctioncategory = get_model('sysfunctioncategory')
                
                fields = ['system', 'sys_abbr', 'begin_date', 'end_date',
                    'version_date', ('mode', 'PARA/TEST_MODE'),
                    ]
                f = {}  #字段列表信息
                c = {}  #保存要转换值的字段信息，key为字段名，value为对应settings中的选项
                def get_key(key, value):
                    """
                    用于反向根据值来获取key，如[('1', '高'), ('2', '低')]，根据'高'得到'1'
                    """
                    from uliweb import settings
                    
                    s = settings.get_var(key, [])
                    for k, v in s:
                        if isinstance(value, unicode):
                            value = value.encode('utf-8')
                        if isinstance(v, unicode):
                            v = value.encode('utf-8')
                            
                        if value == v:
                            return k
                    
                for i, item in enumerate(fields):
                    if isinstance(item, (tuple, list)):
                        c[item[0]] = item[1]
                        f[i] = item[0]
                    else:
                        f[i] = item
                last_sys = None
                i = 0
                for line in open_book(file_contents=data['func_file']['file'].read(), 
                    log=log, begin=1, fields=f):
                    i += 1
                    d = line.copy()
                    #process value convert
                    for k, v in c.iteritems():
                        if k in d:
                            d_v = d[k]
                            d[k] = get_key(v, d_v)
                            
#                        del d['sys_name']
                    if isinstance(d['daily_visit'],int) or isinstance(d['daily_visit'],float) or isinstance(d['daily_visit'],Decimal):
                        pass
                    elif not d['daily_visit'].strip():
                        d['daily_visit']=0
                    
                    sys_id = d.pop('system')
                    if sys_id:
                        s = System.get(System.c.sys_id==sys_id)
                        last_sys = s
                    if not last_sys:
                        flash('第%d行系统简称查询不到，请检查是否没有填写或大小写不一致' % i)
                        return redirect(url_for(SysFunctionView.list, id=id))
                    else:
#                        if not (last_sys.id in (request.user.users_systems.ids())):
##                                print last_sys.id,[request.user.users_systems.ids()],(last_sys.id in (request.user.users_systems.ids()))
#                            flash('你不是导入数据中的系统管理员，无法导入该系统系统功能点，请检查！')
#                            return redirect(url_for(SysFunctionView.list, id=id))
#                        
#                        category = d.pop('category')
#                        if category:
#                           ca = Sysfunctioncategory.get(and_(Sysfunctioncategory.c.name==category,Sysfunctioncategory.c.system==last_sys.id))
#                           d['category'] = ca.id
                        d['system'] = last_sys.id
#                        if isinstance(d['sequence_number'],int):
#                           d['sequence_number'] = str(d['sequence_number'])
#                        d['sequence_number'] = last_sys.sys_id +'_'+ d['function_code']
                        p={}
                        p['begin_date']=d['begin_date']
                        p['end_date']=d['end_date']
                        
                        row = Versionverificationtest.get(and_(Versionverificationtest.c.system==d['system'],Versionverificationtest.c.version_date==d['version_date']))
                        if row:
                            row.update(**d)
                        else:
                            row = Sysfunction(**d)
                        row.save()
                        #创建或更新已创建的任务版本验证测试计划
                        task_dev = Tasks_develop.filter(and_(Tasks_develop.c.task_sys == d['system'],Tasks_develop.c.version_date == d['version_date']))
                        for row_task in task_dev:
                            #处理plan表
                            plan_obj=Plan.get(and_(Plan.c.task==task_dev.id,Plan.c.idn=='0090'))
                            if plan_obj:
                               plan_obj.update(**p)
                            else:
                                plan_obj = Plan(task=task_dev.id, title=u'版本验证测试', type='1', 
                                                end_date=d['end_date'], begin_date=d['begin_date'],
                                                test_type=False,
                                                idn='0090', main_sys=d['system'], is_public=False,
                                                is_reserved=False,
                                                stage='10', weight=0,
                                                )
                            plan_obj.save()
                            plan_obj.systems.add(d['system'])
                            #处理planedit表
                            planedit_obj = Planedit.get(and_(Planedit.c.task==task_dev.id,Plan.c.idn=='0090'))
                            if planedit_obj:
                                planedit_obj.update(**p)
                            else:
                                planedit_obj = Planedit(task=task_dev.id, title=u'版本验证测试', type='1', 
                                                end_date=d['end_date'], begin_date=d['begin_date'],
                                                test_type=False,
                                                idn='0090', main_sys=d['system'], is_public=False,
                                                is_reserved=False,
                                                stage='10', weight=0,
                                                )
                            planedit_obj.save()
                            planedit_obj.systems.add(d['system'])
                            #处理planexecute表
                            planexecute_obj=Planexecute.get(and_(Planexecute.c.task==task_dev.id,
                                                                Planexecute.c.plan==plan_obj.id,
                                                                Planexecute.c.system==d['system']))
                            if planexecute_obj:
                                planexecute_obj.update(**p)
                            else:
                                planexecute_obj=Planexecute(task=task_dev.id, plan=plan_obj.id, type='1', system=d['system']) 
                            
                            planexecute_obj.save()  
                        
                flash('导入成功，共导入%d条记录' % i)
                return redirect(url_for(SysFunctionView.list, id=id))
            except Exception, e:
                log.exception(e)
                flash('处理过程有问题，请与程序员联系')
                return redirect(url_for(SysFunctionView.list, id=id))
    
#        def post_created_form(fcls, model):
#            System = get_model('system')
#            if request.user.department == '2':
#                fcls.system.query = request.user.users_systems.all()
#            elif request.user.department == '3':
#                fcls.system.query = System.all()
    
    from forms import SysFunctionImportForm
    if request.user.department in ('2', '3'):
        view = ImportView('sysfunction', url_for(SysFunctionView.list, id=id), fields=(), 
#                post_created_form=post_created_form, 
            form_cls=SysFunctionImportForm)
        return view.run()
    else:
        flash('你不是开发人员和测试人员，无法导入新测试功能点！')
        return redirect(url_for(SysFunctionView.list, id=id))
